import store from "./store/index.js";
import { addAction, subAction } from "./store/actionCreators.js";

// store.subscribe(() => {
//   console.log(store.getState());
// })

// store.dispatch(addAction(10));
// store.dispatch(subAction(5));

//2. 缺陷：还要到处引入自己定义的函数
// function dispatchAndLogging(action) {
//   console.log("dispatch前：action：", action);
//   store.dispatch(action)
//   console.log("dispatch后：new state：", store.getState());
// }
 
// dispatchAndLogging(addAction(10));
// dispatchAndLogging(addAction(5));


//3.优化
//hack技术：monkeyingpatch
// const next = store.dispatch;
// function dispatchAndLogging(action) {
//   console.log("dispatch前：action：", action);
//   next(action)
//   console.log("dispatch后：new state：", store.getState());
// }

// store.dispatch = dispatchAndLogging;
// store.dispatch(addAction(10));
// store.dispatch(addAction(5));

//4.封装
function patchLogging(store) {
  const next = store.dispatch;
  function dispatchAndLogging(action) {
    console.log("dispatch前：action：", action);
    next(action)
    console.log("dispatch后：new state：", store.getState());
  }  
  // 返回出去 不作操作 就变成了纯函数
  // return dispatchAndLogging;
  store.dispatch = dispatchAndLogging;
}
patchLogging(store);

//封装patchThunk功能
function patchThunk(store) {
  const next = store.dispatch;
  function dispatchAndThunk(action) {
    if (typeof action === "function") {
      action(store.dispatch, store.getState)
    } else {
      next(action)
    }
  }
  // return dispatchAndThunk;
  store.dispatch = dispatchAndThunk;
}
patchThunk(store);

// store.dispatch(addAction(10))
// store.dispatch(addAction(5))

// function foo(dispatch, state) {
//   dispatch(subAction(10))
// }
// store.dispatch(foo)

//5. 封装applyMiddleware
function applyMiddlewares(...middlewares) {
  middlewares.forEach(middleware => {
    // store.dispatch = middleware(store)   上面返回函数时使用这里
    
    middleware(store)
  })
}
applyMiddlewares(patchLogging, patchThunk)